package org.apache.jmeter.functions;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class MyFunction extends AbstractFunction{

    //自定义function的描述
    private static final List<String> desc = new LinkedList<String>();
    //function名称
    private static final String KEY = "__MyFunction";

    static {
        desc.add("随机数最大值");
    }

    /**
     * 最大值参数
     */
    private CompoundVariable maxValue;

    @Override
    public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
        String maxValueStr = String.valueOf(maxValue.execute());
        Random random = new Random();
        int anInt = random.nextInt(Integer.parseInt(maxValueStr));
        return String.valueOf(anInt);
    }

    @Override
    public void setParameters(Collection<CompoundVariable> collection) throws InvalidVariableException {
        checkParameterCount(collection, 1);
        Object[] values = collection.toArray();
        maxValue = (CompoundVariable) values[0];
    }

    @Override
    public String getReferenceKey() {
        return KEY;
    }

    @Override
    public List<String> getArgumentDesc() {
        return desc;
    }
}
